package com.killer.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.killer.io.Resource;
import com.killer.pojo.Configuration;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.util.List;
import java.util.Properties;

/**
 * 该类负责解析sqlMapConfig.xml，封装Configuration对象
 */
public class XmlConfigBuilder {

    private Configuration configuration;

    public XmlConfigBuilder() {
        this.configuration = new Configuration();
    }

    public Configuration parseConfiguration(InputStream inputStream) throws DocumentException, ClassNotFoundException {
        SAXReader reader = new SAXReader();
        Document document = reader.read(inputStream);
        //获取sqlMapConfig的根标签,即<Configuration>
        Element rootElement = document.getRootElement();
        //获取dataSource标签
        Element dataSourceElement = rootElement.element("dataSource");
        //获取dataSource标签下的所有配置信息
        // SelectNodes("item")从当前节点的儿子节点中选择名称为 item 的节点。
        List<Element> propertyElements = dataSourceElement.selectNodes("property");
        Properties properties = new Properties();
        for (Element propertyElement : propertyElements) {
            String name = propertyElement.attributeValue("name");
            String value = propertyElement.attributeValue("value");
            properties.put(name, value);
        }
        DruidDataSource druidDataSource=new DruidDataSource();
        druidDataSource.setDriverClassName(properties.getProperty("driver"));
        druidDataSource.setUrl(properties.getProperty("url"));
        druidDataSource.setUsername(properties.getProperty("user"));
        druidDataSource.setPassword(properties.getProperty("password"));
        configuration.setDataSource(druidDataSource);
        //解析mapper文件,封装mappedStatement对象
        parseMapper(rootElement);
        return configuration;
    }


    private void parseMapper(Element rootElement) throws DocumentException, ClassNotFoundException {
        XmlMapperBuilder mapperBuilder = new XmlMapperBuilder(configuration);
        //SelectNodes("//item")
        //从任意位置的节点上选择名称为 item 的节点。
        // 要重点突出这个任意位置，它不受当前节点的影响，
        // 也就是说假如当前节点是在第 100 层（有点夸张），也可以选择第一层的名称为 item 的节点。
        List<Element> mapperElements = rootElement.selectNodes("//mapper");
        for (Element mapperElement : mapperElements) {
            //先获取对应的路径
            String path = mapperElement.attributeValue("resource");
            //加载该配置文件
            InputStream mapperInputStream = Resource.getResourceAsStream(path);
            mapperBuilder.parse (mapperInputStream);
        }

    }

}
